
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>面试被问 Java为什么有这么多O - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>面试被问 Java为什么有这么多O - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "根据文档，引入PO、DTO、VO等多种Java对象模型的核心目的是什么？",
    "options": [
      "为了提高数据库的查询性能。",
      "为了减少项目中类的总数量。",
      "实现“关注点分离”，让每一层架构只处理自己的特定职责。",
      "为了强制所有开发者遵循统一的编码规范。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "文档开篇就指出，这些不同的对象模型是为了解决软件工程中的核心问题：“关注点分离”。通过为不同架构层（持久层、业务层、表现层）设计专用的对象，可以使代码结构更清晰、职责更明确，从而提高可维护性和可扩展性。",
    "source": "文档中「1、Java对象模型的起源与演变」部分",
    "hint": "文档提到，如果所有功能都挤在一个对象里，就像把所有衣物都塞进同一个抽屉。"
  },
  {
    "question": "在一个电商网站的商品详情页，需要将价格显示为 \"¥199.99\"，并将库存数量显示为 \"有货\" 或 \"缺货\"。哪个对象模型最适合承载这些为前端展示而格式化后的数据？",
    "options": [
      "PO (Persistent Object)",
      "VO (View Object)",
      "DTO (Data Transfer Object)",
      "BO (Business Object)"
    ],
    "correctAnswerIndex": 1,
    "explanation": "VO (View Object) 的核心职责就是为前端展示服务。它就像“化妆师”，专门将后端原始数据（如数据库中的 `BigDecimal` 类型的价格和 `Integer` 类型的库存）转换和包装成前端友好、可直接显示的格式（如 `String` 类型的 \"¥199.99\" 和 \"有货\"）。",
    "source": "文档中「2、常见的Java对象模型」的「VO (View Object)」部分",
    "hint": "文档中哪个对象被比喻为“化妆师”，负责将原始数据进行包装和美化？"
  },
  {
    "question": "文档中强调，直接在Controller层向前端返回PO (Persistent Object) 是一种不好的做法。这会带来多种问题，其中最严重的安全风险是什么？",
    "options": [
      "会导致前端无法解析复杂的对象结构。",
      "会因为包含了过多的业务逻辑而导致前端代码混乱。",
      "可能会无意中暴露数据库中的敏感字段，如密码哈希值。",
      "会显著增加服务器的内存消耗。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "PO对象与数据库表结构一一对应，通常包含所有字段。如果直接将其返回给前端，像用户的密码哈希（`password`）、内部创建时间（`created_at`）等敏感或不必要的字段就可能被泄露，给系统带来严重的安全隐患。使用DTO可以精确控制只暴露必要的、安全的字段。",
    "source": "文档中「4、面试官最爱问的对象模型问题」的「\"为什么需要 DTO，直接使用 Entity 不行吗？\"」部分",
    "hint": "思考一下 `UserPO` 中可能包含哪些不应该被前端获取到的字段。"
  },
  {
    "question": "一个用户对象需要根据其历史订单总额来判断是否可以升级为VIP会员。这个“判断能否升级”的逻辑应该封装在哪个对象模型中？",
    "options": [
      "BO (Business Object)",
      "PO (Persistent Object)",
      "VO (View Object)",
      "DTO (Data Transfer Object)"
    ],
    "correctAnswerIndex": 0,
    "explanation": "BO (Business Object) 被定义为封装业务逻辑和规则的核心。像 `canUpgradeToVip()` 这样的方法，它需要组合多个数据（用户信息、订单信息）并根据预设的业务规则（如消费满1000元）进行计算和决策，这正是BO的职责所在。文档中将其比喻为“业务专家”。",
    "source": "文档中「2、常见的Java对象模型」的「BO (Business Object)」部分",
    "hint": "哪个对象被比喻为“业务专家”，负责做出业务决策？"
  },
  {
    "question": "关于对象转换工具 MapStruct 和 ModelMapper，它们在实现机制上的根本区别是什么，这如何影响它们的性能？",
    "options": [
      "MapStruct在编译时生成映射代码，运行时无额外开销，性能高；而ModelMapper在运行时使用反射进行映射，存在性能开销。",
      "MapStruct只能处理简单的一对一映射，而ModelMapper可以处理复杂的嵌套映射。",
      "MapStruct是Spring框架的一部分，而ModelMapper是一个独立的第三方库。",
      "MapStruct通过XML配置映射规则，而ModelMapper使用注解。"
    ],
    "correctAnswerIndex": 0,
    "explanation": "文档明确对比了两者的处理方式。MapStruct是一个代码生成器，在编译阶段就已经创建了具体的Java映射代码，其运行效率接近手动编写的代码。相反，ModelMapper依赖Java的反射机制在程序运行时动态地查找和调用方法，这个过程相比直接的方法调用会有额外的性能损耗。",
    "source": "文档中「6、MapStruct 与 ModelMapper」的「两者对比」表格",
    "hint": "一个工具在“编译时”工作，另一个在“运行时”工作，这带来了性能上的差异。"
  },
  {
    "question": "在进行对象转换时，如果一个 `Department` 对象包含一个 `Employee` 列表，而每个 `Employee` 对象又反向引用了它所属的 `Department` 对象，这最可能导致什么问题？",
    "options": [
      "数据丢失，`Employee` 的部门信息会无法正确转换。",
      "循环引用，可能在序列化时导致无限递归和栈溢出错误。",
      "性能问题，因为需要额外查询数据库来加载 `Department` 信息。",
      "类型转换异常，因为 `Department` 和 `Employee` 类型不兼容。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "当两个或多个对象相互引用，形成一个闭环时，就产生了循环引用。在进行序列化（例如，使用Jackson库将对象转换为JSON字符串）或使用某些映射工具时，程序会尝试遍历这个无限循环的引用链，最终耗尽调用栈空间，导致 `StackOverflowError`。文档中提到了使用 `@JsonIdentityInfo` 注解作为一种解决方案。",
    "source": "文档中「3、对象模型的实战应用」的「常见的对象转换陷阱」部分",
    "hint": "想一想，当一个工具试图完整地打印出A，而A里面有B，B里面又有A时，会发生什么？"
  },
  {
    "question": "当客户端（如Web前端或移动App）需要调用一个接口来注册新用户时，它会提交用户名、密码、邮箱和验证码。服务器端的Controller接收这些数据最适合使用哪种对象模型？",
    "options": [
      "PO (Persistent Object)",
      "VO (View Object)",
      "BO (Business Object)",
      "DTO (Data Transfer Object)"
    ],
    "correctAnswerIndex": 3,
    "explanation": "DTO (Data Transfer Object) 的核心职责是在不同层或系统边界之间传输数据。在这种场景下，`UserRegistrationDTO` 可以精确地定义注册接口所需的所有字段（`username`, `password`, `email`, `captchaCode`），它充当了表现层和业务层之间的“信使”，既不暴露底层数据库结构（PO），也不包含业务逻辑（BO），是理想的数据载体。",
    "source": "文档中「2、常见的Java对象模型」的「DTO (Data Transfer Object)」部分",
    "hint": "哪种对象被描述为“层与层之间的信使”，专门用于携带必要的信息？"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  